package org.AftpBrocast;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.*;
import java.util.*;


/**
 * AFtpBrocastServerThread is used to brocast the AftpServer's ip and port information
 * @author andy yang buptjunjun@gmail.com
 */
public class AFtpBrocastServerThread extends Thread
{
	private MulticastSocket msocket = null;
	private  String groupIp   = null;
	private  String ServerIp  = null;
	private     int serverPort  = 0;
	private     int clientPort = 0;
	private     int ftpPort    = 0; 
 	private     int interval   = 1000;
	
	
	public AFtpBrocastServerThread(String groupIp, int serverPort,int clientPort,int ftpPort,int interval) 
	{
		this.groupIp = groupIp;
		this.serverPort = serverPort;
		this.clientPort = clientPort;
		this.ftpPort = ftpPort;
		this.interval = interval;
		
		try 
		{
			//get the IP address of local host 
			this.ServerIp = InetAddress.getLocalHost().getHostAddress();
			
			//init the socket 
			this.msocket = new MulticastSocket(this.serverPort);
			InetAddress inetaddr = InetAddress.getByName(this.groupIp);
			this.msocket.joinGroup(inetaddr);
		} 
		catch (Exception e) 
		{
			msocket = null;
			e.printStackTrace();
		}
	}

    public void run() 
    {
        if(this.msocket == null) return ;
        
        //data to brocast
        String data  = this.ServerIp+","+this.ftpPort;
        System.out.println("# send data: " + data);
        byte[] data2send = null;
        
        //set the charactor to utf-8
		try {data2send = data.getBytes("UTF-8");} 
		catch (UnsupportedEncodingException e1) 
		{	
			e1.printStackTrace();
		}
		
        InetAddress inetaddr = null;
		try
		{
			inetaddr = InetAddress.getByName(this.groupIp);
            DatagramPacket packet = new DatagramPacket(data2send,data2send.length,inetaddr,this.clientPort);
          
            while(true)
            {
            	try
            	{
	            	this.msocket.send(packet);
	            	//System.out.println("# send a packet");
	            	Thread.currentThread().sleep(this.interval);
	            	
	            	
            	}catch(Exception e){ e.printStackTrace(); }
            }
		}
		catch (Exception e) { e.printStackTrace();}
		finally{ if(this.msocket!=null) this.msocket.close(); }
		
    }
    
    public static void main(String [] args)
    {
    	AFtpBrocastServerThread client = new AFtpBrocastServerThread("230.0.0.1",3721,3722,21,1000);
    	client.start();
    	
    }
	
}
